<?php

namespace App\Service;

use App\Models\EwReco;

class RecoService extends BaseService
{
	/**
	 * [getRecoList 获取推荐相关Id]
	 * @param  [type] $params->table_id [description]
	 * @param  [type] $params->list_id  [description]
	 * @return [type]                   [description]
	 */
	public static function getRecoList($params)
	{
		$data = EwReco::find(['columns' => 'reco_id', 'conditions' => 'table_id = ' . intval($params->table_id) . ' AND list_id = '.intval($params->list_id)])->toArray();
		$arr = [];
		foreach ($data as $key => $value) {
			$arr[]=$value['reco_id'];
		}
		return $arr;
	}

	/**
	 * [saveRecoList 将推荐相关Id保存到数据库 ]
	 * @param  [type] $params->table_id [description]
	 * @param  [type] $params->list_id  [description]
	 * @param  [type] $params->reco_ids [description]
	 * @return [type]                   [description]
	 */
	public static function saveRecoList($params)
	{
		self::deleteRecoList($params);

		if ($params->reco_ids){
			$reco_id_arr = explode(',', $params->reco_ids);
			foreach ($reco_id_arr as $reco_id) {
				$raw = new EwReco();
				$arr = [];
				if ($params->list_id != $reco_id){//不能推荐本身
					$arr['table_id'] = intval($params->table_id);
					$arr['list_id']  = intval($params->list_id);
					$arr['reco_id']  = intval($reco_id);
					$info = EwReco::findFirst(['conditions' => 'table_id = ' . $arr['table_id'].' AND list_id = ' . $arr['list_id'].' AND reco_id = '. $arr['reco_id']]);

					if (!$info)
					$raw->save((array)$arr);
				}
				
			}
			return TRUE;
		}
	}

	/**
	 * [deleteRecoList 删除原相关推荐]
	 * @param  [type] $params->table_id [description]
	 * @param  [type] $params->list_id  [description]
	 * @return [type]                   [description]
	 */
	public static function deleteRecoList($params)
	{
		$data = EwReco::find(['conditions' => 'table_id = ' . intval($params->table_id) . ' AND list_id = '.intval($params->list_id)]);
		foreach ($data as $model) {
			$model->delete();
		}

		return TRUE;
	}
	
}